package com.young.serialtransfer;

import com.fazecast.jSerialComm.SerialPort;
import org.springframework.stereotype.Service;


/**
 * @className: SerialPortForwarder
 * @author: Young
 * @date: 2025/2/7 22:12
 * @Version: 1.0
 * @description:
 */
@Service
public class SerialPortForwarder {

    public static void main(String[] args) {
        SerialPort physicalPort = SerialPort.getCommPort("COM1");
        SerialPort virtualPort = SerialPort.getCommPort("COM3");

        // 设置串口参数，这里以 9600 波特率为例
        setSerialPortParams(physicalPort);
        setSerialPortParams(virtualPort);

        // 打开串口
        if (!openSerialPort(physicalPort)) {
            System.err.println("无法打开物理串口 COM1");
            return;
        }
        if (!openSerialPort(virtualPort)) {
            System.err.println("无法打开虚拟串口 COM3");
            physicalPort.closePort();
            return;
        }

        // 创建并启动数据转发线程
        new Thread(new DataForwarder(physicalPort, virtualPort)).start();
        new Thread(new DataForwarder(virtualPort, physicalPort)).start();

        System.out.println("开始进行串口数据转发...");
    }

    // 设置串口参数的方法
    private static void setSerialPortParams(SerialPort port) {
        port.setBaudRate(9600);
        port.setNumDataBits(8);
        port.setNumStopBits(SerialPort.ONE_STOP_BIT);
        port.setParity(SerialPort.NO_PARITY);
    }

    // 打开串口的方法
    private static boolean openSerialPort(SerialPort port) {
        return port.openPort();
    }

    // 数据转发线程类
    static class DataForwarder implements Runnable {
        private final SerialPort sourcePort;
        private final SerialPort destinationPort;

        public DataForwarder(SerialPort sourcePort, SerialPort destinationPort) {
            this.sourcePort = sourcePort;
            this.destinationPort = destinationPort;
        }

        @Override
        public void run() {
            byte[] buffer = new byte[1024];
            while (sourcePort.isOpen() && destinationPort.isOpen()) {
                if (sourcePort.bytesAvailable() > 0) {
                    int numRead = sourcePort.readBytes(buffer, buffer.length);
                    destinationPort.writeBytes(buffer, numRead);
                }
            }
        }
    }
}
